import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useUserStore = defineStore('user', () => {
  // State
  const userInfo = ref(null)
  const token = ref(localStorage.getItem('token') || '')
  const isLoggedIn = ref(!!localStorage.getItem('isLoggedIn'))

  // Actions
  const login = (credentials) => {
    // 模拟登录（实际项目中应调用API）
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        if (credentials.username && credentials.password) {
          const user = {
            id: '001',
            username: credentials.username,
            name: credentials.username,
            role: 'doctor'
          }
          
          userInfo.value = user
          token.value = 'mock-token-' + Date.now()
          isLoggedIn.value = true
          
          localStorage.setItem('isLoggedIn', 'true')
          localStorage.setItem('username', credentials.username)
          localStorage.setItem('token', token.value)
          
          resolve(user)
        } else {
          reject(new Error('用户名或密码错误'))
        }
      }, 1000)
    })
  }

  const logout = () => {
    userInfo.value = null
    token.value = ''
    isLoggedIn.value = false
    
    localStorage.removeItem('isLoggedIn')
    localStorage.removeItem('username')
    localStorage.removeItem('token')
  }

  const updateUserInfo = (info) => {
    userInfo.value = { ...userInfo.value, ...info }
  }

  return {
    userInfo,
    token,
    isLoggedIn,
    login,
    logout,
    updateUserInfo
  }
})

